package com.tutorial.webservices.saaj.client;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;

import javax.xml.namespace.QName;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.Node;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;

import org.w3c.dom.Element;

public class SimpleSaajClient {

    /**
     * @param args
     */
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
	// TODO Auto-generated method stub
	try {
	    MessageFactory messageFactory = MessageFactory.newInstance();
	    SOAPMessage request = messageFactory.createMessage();
	    SOAPHeader header = request.getSOAPHeader();
	    // Remove header
	    header.detachNode();
	    //Create message
	    SOAPBody body = request.getSOAPPart().getEnvelope().getBody();
	    QName qName = new QName("http://www.tutorial.com", "echo", "m"); //$NON-NL-1$  //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
	    body.addBodyElement(qName).addChildElement(new QName("request-message")).addTextNode("OK"); //$NON-NLS-1$ //$NON-NLS-2$
	    // Create connection
	    SOAPConnectionFactory connFactory = SOAPConnectionFactory.newInstance();
	    SOAPConnection connection = connFactory.createConnection();
	    URL endpoint = new URL("http://localhost:8080/saaj/saajservlet");
	    // Response
	    SOAPMessage response = connection.call(request, endpoint );
	    SOAPBody responseBody = response.getSOAPBody();
	    Iterator<Node> iterator = responseBody.getChildElements();
	    while(iterator.hasNext()) {
		Node node = iterator.next();
		if(node.getNodeType() == Node.ELEMENT_NODE) {
		    System.out.println(((Element)node).getNodeName());
		}
	    }
	} catch (SOAPException e) {
	    e.printStackTrace();
	} catch (MalformedURLException e) {
	    e.printStackTrace();
	}
	
    }

}
